package com.sluggard.ai;

/**
 * 类描述：
 *
 * @author lizheng
 * @created 2025/4/26 20:30
 */
import javax.sound.sampled.*;
import java.io.*;

public class MicrophoneRecorder {
    // 音频格式参数
    private static final float SAMPLE_RATE = 44100.0f;  // 采样率
    private static final int SAMPLE_SIZE = 16;         // 位深度
    private static final int CHANNELS = 1;             // 单声道
    private static final boolean SIGNED = true;        // 有符号
    private static final boolean BIG_ENDIAN = false;   // 小端序

    private TargetDataLine targetDataLine;

    public static void main(String[] args) {
        MicrophoneRecorder recorder = new MicrophoneRecorder();
        try {
            System.out.println("开始录音...（10秒后自动停止）");
            AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
            File outputFile = new File("recording.wav");

            // 开始录音
            recorder.startRecording();

            // 创建录音线程
            Thread recordingThread = new Thread(() -> {
                try {
                    recorder.saveAudio(outputFile, fileType);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            recordingThread.start();

            // 录音持续10秒
            Thread.sleep(10000);

            // 停止录音
            recorder.stopRecording();
            System.out.println("录音已保存至: " + outputFile.getAbsolutePath());

        } catch (LineUnavailableException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 初始化音频格式
    private AudioFormat getAudioFormat() {
        return new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                SAMPLE_RATE,
                SAMPLE_SIZE,
                CHANNELS,
                (SAMPLE_SIZE / 8) * CHANNELS,
                SAMPLE_RATE,
                BIG_ENDIAN
        );
    }

    // 开始录音
    public void startRecording() throws LineUnavailableException {
        AudioFormat format = getAudioFormat();
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        // 检查系统是否支持该格式
        if (!AudioSystem.isLineSupported(info)) {
            System.err.println("不支持的音频格式");
            System.exit(1);
        }

        // 获取并打开目标数据线（麦克风）
        targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
        targetDataLine.open(format);
        targetDataLine.start();
    }

    // 保存音频到文件
    public void saveAudio(File file, AudioFileFormat.Type fileType) throws IOException {
        AudioInputStream ais = new AudioInputStream(targetDataLine);
        AudioSystem.write(ais, fileType, file);
    }

    // 停止录音
    public void stopRecording() {
        targetDataLine.stop();
        targetDataLine.close();
    }
}